<template>
  <TabBar />
  <!-- GL 合作意向函 -->
  <Popup ref="GLaSignRef">
    <Pconfirm cancel-text="稍后签署" confirm-text="立即签署" tip-text="你有一份合作申请书需要签署，是否现在签署？" @cancel="GLaSignRefChange" @confirm="GLaSignRefSubmit" />
  </Popup>
  <!--电子合同签约服务弹框  -->
  <up-popup v-model:show="showPrivacy" mode="bottom" round="40">
    <div class="pricacyPop">
      <div class="title">授权提醒</div>
      <div class="tips">电子合同签约服务由我们的授权合作伙伴深圳法大大网络科技有限公司(“法大大”)提供。为提供该服务，您同意我们将您的个人信息(姓名、身份证号码、电话号码)共亨给授权合作伙伴。</div>
      <div class="options">
        <div class="firstPrav">
          <up-checkbox v-model:checked="aloneChecked1" active-color="#FF8002" used-alone @change="changePrivacy1" />
          <div class="rightItem">
            <div class="fchkb">
              我已仔细阅读并同意第三方相关隐私政策(请长按复制网址
              <span class="schkb" @tap.stop="copyToClipboard({
                content: 'https://agreement-os1.fadada.com/46d9beae63024d469cb971ce5757978a',
                successTip: '链接复制成功,请前往浏览器打开',
                failTip: '链接复制失败',
              })"
              >https://agreement-os1.fadada.com/46d9beae63024d469cb971ce5757978a</span>
              至浏览器访问第三方隐私政策)。
            </div>
          </div>
        </div>
        <div class="secondPrav">
          <up-checkbox v-model:checked="aloneChecked2" active-color="#FF8002" used-alone @change="changePrivacy2" /><div class="rightInfo">我同意将我的个人信息共亨给第三方。</div>
        </div>
      </div>
      <div class="line" />
      <div class="foot">
        <Button :styles="{ width:'300rpx',height:'70rpx' }" size="M" type="solid" @confirm="cancelPop">取消</Button>
        <Button :disabled="!(aloneChecked1 && aloneChecked2)" :styles="{ width:'300rpx',height:'70rpx' }" size="M" @confirm="agPop">同意</Button>
      </div>
    </div>
  </up-popup>

  <scroll-view :scroll-y="true" :show-scrollbar="true" class="wrap">
    <div class="banner">
      <div class="swiper-dot-d">
        <div
          v-for="(d, i) in bannerList"
          :key="d.id"
          :style="{
            width: i === bannerCurrent ? '60rpx' : '20rpx',
            background: i === bannerCurrent ? '#ffffff' : (i === bannerCurrent + 1 || (bannerCurrent === bannerList.length - 1 && i === 0)) ? '#ffffff' : 'rgba(255, 255, 255, 0.35)',
          }"
          class="swiper-dot-item"
        />
      </div>
      <swiper
        :interval="3000"
        autoplay
        circular
        style="height: 100%"
        @change="bannerChange"
      >
        <swiper-item v-for="d in bannerList" :key="d.id">
          <Image
            :name="d.cover"
            height="590"
            overspread
            width="100vw"
            @tap.stop="goArticle(d)"
          />
        </swiper-item>
      </swiper>
    </div>
    <div class="body">
      <div class="body_box">
        <div class="item_box">
          <div class="flex_sb_cen nav_bar">
            <div
              v-for="(v, k) in statistic.enum"
              :key="k"
              class="item"
              @tap.stop="goView(v?.path, v?.params)"
            >
              <div class="num">{{ v.num }}</div>
              <div class="label">{{ v.title }}</div>
            </div>
          </div>
          <div class="flex_sb_cen" style="flex-wrap: wrap">
            <div
              v-for="(d, i) in functionEntry"
              :key="i"
              class="item1"
              @tap.stop="goView(d?.path, d?.params)"
            >
              <Image :name="d.name" :size="d.size" oss />
              <div class="flex1 ml20">
                <div class="title">{{ d.title }}</div>
                <div class="sub_title">{{ d.subTitle }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="new_info" @tap.stop="goView('informList')">
          <div class="title">
            <div class="label">最近消息</div>
            {{ newsText }}
            <Icon v-if="newsNumber" height="40" name="icon-hongdian" size="40" />
            <Icon :styles="{opacity: '0.45'}" height="40" name="icon-youjiantou" size="30" />
          </div>
          <div v-if="recentInfo?.length < 1" class="flex_cen_cen">
            <Image height="198" name="no_data" oss width="140" />
          </div>
          <div
            v-for="d in recentInfo"
            v-else
            :key="d.time"
            class="item"
          >
            <div class="info">
              {{ d?.begin }}
              <div class="message textLineHidden">{{ d.content }}</div>
              {{ d?.end }}
            </div>
            <div class="line" />
            <div class="time">{{ d.time }}</div>
          </div>
        </div>
      </div>
    </div>
  </scroll-view>
  <Popup ref="popupRef1">
    <Pconfirm
      :confirm-text="popInfo.confirmText"
      :is-two-btn="false"
      :tip-title="popInfo.title"
      @confirm="operateFn"
    >
      <template #tip>
        <div style="letter-spacing: 6rpx">{{ popInfo.staticContent }}</div>
      </template>
    </Pconfirm>
  </Popup>
  <Popup ref="popupRef2">
    <Pconfirm
      :styles="{width: '670rpx',borderRadius: '24rpx', paddingRight: '24rpx', paddingLeft: '26rpx'}"
      :tip-title="popInfo.title"
    >
      <template #tip>
        <div class="static_content">{{ popInfo.staticContent }}</div>
        <div v-if="popInfo.dynamicContent" class="dynamic_content mt26" v-html="popInfo.dynamicContent" />
      </template>
      <template #twoBtn>
        <div class="flex_sb_cen" style="width: 100%">
          <Button :styles="{width: '292rpx'}" type="solid" @confirm="popupRef2.change()">{{ popInfo.cancelText }}</Button>
          <Button :styles="{width: '292rpx'}" @confirm="operateFn">{{ popInfo.confirmText }}</Button>
        </div>
      </template>
    </Pconfirm>
  </Popup>
  <div class="ai_chat flex_sb_cen">
    <div v-show="isShowAiTip" class="bubble">
      <div>如果您遇到使用问题，可以随时问我哦。</div>
      <div class="base_color mt10" @tap="isShowAiTip = false">我知道了</div>
      <div class="triangle_black" />
      <div class="triangle_white" />
    </div>
    <div class="ai_avatar">
      <Image name="ai/ai_chat" oss size="120" type="png" @tap="goAIChatFn" />
      <div class="ai_chat_text">AI客服</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import {
  getReq,
  postReq,
  LStorage,
  Router,
  copyToClipboard,
  onShow,
  storeCommit,
  onHide,
} from '@U/common'
import Image from '@C/Image.vue'
import Icon from '@C/Icon.vue'
import {
  getBanner,
  getBannerInfo,
  getPersonCardMsg,
  getMyTeam,
  getPopupInfo,
} from '@P/Workbench/request'
import { weixinSubscription } from '@U/Auth'
import { Msg } from '@C/Msg'
import Popup from '@C/Popup.vue'
import Button from '@C/Button.vue'
import Pconfirm from '@C/Pconfirm.vue'
import { getPersonAccountDefAuth } from '@P/Auth/request'
import type { IObj, IObjArray } from '@/interface'
import functionEntryEnum from './functionEntry.json'
import statisticDataEnum from './statistic.json'

// 轮播图
const bannerList = ref(<IObjArray>[
  {
    articleId: 1,
    cover: `${import.meta.env.VITE_SHOUDAO_OSS_URL}/banner/def_banner1.png`,
  },
])
// 轮播图列表
async function getBannerList() {
  const { data } = await getBanner().finally(() => {})
  if (data && data.rows.length) {
    bannerList.value = data.rows
  }
}
// 轮播图虚拟滑块位置
const bannerCurrent = ref(0)
const bannerChange = (e: IObj) => { bannerCurrent.value = e.detail.current }
const isFirst = ref(true)
const goArticle = async (obj:IObj) => {
    if (`${obj.materialId}`.length === 1 || !obj.materialId) return
    const { code, data, msg } = await getBannerInfo({ materialId: obj.materialId }).finally(() => {})
    if (code === 200) {
      // {id: 1, name: "彩页"} articleInfo
      // {id: 2, name: "软文"} articleInfo
      // {id: 3, name: "海报"} margetCenterInfo
      // {id: 4, name: "话术"} articleInfo
      // {id: 5, name: "图片"} margetCenterInfo
      // {id: 6, name: "视频"} margetCenterDetails
      // {id: 7, name: "音频"} margetCenterDetails
      // {id: 8, name: "文档"} margetCenterDetails
      if (isFirst.value) {
        isFirst.value = false
        if (obj.materialTypeId === 1 || obj.materialTypeId === 2 || obj.materialTypeId === 4) return Router.push('articleInfo', { materialId: obj.materialId, pageTitle: obj.materialTypeId === 1 ? '彩页' : obj.materialTypeId === 2 ? '软文' : '话术' })
        if (obj.materialTypeId === 3 || obj.materialTypeId === 5) {
          const title = obj.materialTypeId === 3 ? '海报' : '图片'
          return Router.push('gl_market_info', { title, id: obj.materialTypeId, open: true, img: data.content, materialId: obj.materialId })
        }
        if (obj.materialTypeId === 6 || obj.materialTypeId === 7 || obj.materialTypeId === 8) {
          const pageTitle = obj.materialTypeId === 6 ? '视频' : obj.materialTypeId === 7 ? '音频' : '文档'
          return Router.push('gl_market_details', { materialId: obj.materialId, pageTitle })
        }
      }
    } else {
      Msg({ msg })
    }
}
// 功能入口
const functionEntry = computed(() => (functionEntryEnum as IObj).GL)

// 统计数据
const statistic = computed(() => (statisticDataEnum as IObj).GL)

const multiNumber = ref(0)
const statisticTemp: IObjArray = []
watch(
    () => multiNumber.value,
    (newVal: number, oldVal: number) => {
      if (oldVal > 0 && newVal === 0) {
        let data: IObj = {}
        statisticTemp.forEach((d: IObj) => {
          data = { ...data, ...d }
        })
        Object.keys(statistic.value.enum).forEach((key: string) => {
          statistic.value.enum[key].num = data[key] ?? '--'
        })
      }
    },
)
async function getStatistic() {
  const apiPath: string | Array<string> = statistic.value.request
  if (typeof apiPath === 'string') {
    const { data } = await getReq(apiPath)
    Object.keys(statistic.value.enum).forEach((key: string) => {
      statistic.value.enum[key].num = data[key] ?? '--'
    })
  } else {
    multiNumber.value = apiPath.length
    for (const path of apiPath) {
      console.log('path', path)
      const { data } = await getReq(path)
      multiNumber.value -= 1
      statisticTemp.push(data)
    }
  }
  const { data } = await getMyTeam()
  statistic.value.enum.subPartnerCount.num = data.total
}
getStatistic()
// 消息
const recentInfo = ref(<IObjArray>[])
const newsNumber = ref(0)
const newsText = computed(() => (newsNumber.value ? `${newsNumber.value}条新消息` : ''))
// 最近信息
async function getRecentInfoFn() {
  const { data } = await getPersonCardMsg().finally(() => {})
  newsNumber.value = data.count
  recentInfo.value = data.list
}
// 去页面
const goView = (path: string, params?: IObj) => {
  weixinSubscription()
  if (!path) return
  Router.push(path, params)
}

// GL 合作意向函
const GLaSignRef = ref()
const GLaSignRefSubmit = () => {
  GLaSignRefChange()
  if (isFirst.value) {
    isFirst.value = false
    setTimeout(() => Router.push('signList', {}), 300)
  }
}
const GLaSignRefChange = () => {
  GLaSignRef.value.change()
}

// 电子合同签约服务 弹框
const showPrivacy = ref(false)
const aloneChecked1 = ref(false)
const aloneChecked2 = ref(false)
const cancelPop = () => {
  showPrivacy.value = false
  setTimeout(() => {
    aloneChecked1.value = false
    aloneChecked2.value = false
    showPrivacy.value = true
  }, 300)
}
const agPop = async () => {
  if (aloneChecked1.value && aloneChecked2.value) {
    LStorage('isAgreePrivacy', true)
    showPrivacy.value = false
  }
}

const changePrivacy1 = (val: boolean) => {
  aloneChecked1.value = val
}
const changePrivacy2 = (val: boolean) => {
  aloneChecked2.value = val
}
const popupRef1 = ref()
const popupRef2 = ref()
const operateFn = async () => {
  if (popInfo.type === 1) {
    Router.redirect('operation', { key: 'gl_hhr_taxationForm' })
    popupRef1.value.change()
  }
  if (popInfo.type === 2 || popInfo.type === 3) {
    const { code, data } = await postReq('/api/channel-agent/popup/finish', { id: popInfo.id }).finally(() => {
      popInfo.id = ''
    })
    if (code === 200) {
      popupRef2.value.change()
      Router.push('hold_main_body')
    } else {
      Msg({ msg: data?.msg })
    }
  }
}
const popInfo = reactive({
  type: 0,
  title: '',
  confirmText: '',
  cancelText: '',
  staticContent: '',
  dynamicContent: '',
  id: '',
})
const getPopupInfoFn = async () => {
  const { code, data } = await getPopupInfo().finally(() => {})
  if (code === 200) {
    /**
     * type: 1跟进 2持有主体资料待完善 3 持有主体资料被驳回
     * */
    const { needPop, state, type, content, id } = data
    if (needPop) {
      popInfo.type = type
      if (type === 1 && state === 3) {
        popInfo.confirmText = '立即修改'
        popInfo.staticContent = '您的跟进记录被驳回，请进行修改'
        popupRef1.value.change()
      }
      if (type === 2 && state === 0) {
        popInfo.id = id
        popInfo.title = '资料缺失提醒'
        popInfo.confirmText = '去完善资料'
        popInfo.cancelText = '暂不完善'
        popInfo.staticContent = '您持有的服务主体资料不完整，请进行补充。需要补充资料的服务主体：'
        // popInfo.dynamicContent = content.split('<br />').map(item => `<div style="margin-bottom:30rpx;">${item}<br /></div>`).join('')
        popInfo.dynamicContent = content
        popupRef2.value.change()
      }
      if (type === 3 && state === 0) {
        popInfo.id = id
        popInfo.title = '提示'
        popInfo.confirmText = '立即修改'
        popInfo.cancelText = '稍后修改'
        popInfo.staticContent = `您的“${content}”资料被驳回，为避免影响您的业务，请尽快修改`
        popupRef2.value.change()
      }
    }
  }
}
// 获取智客信息
const getZhiKeInfo = async () => {
  const { code, data } = await getPersonAccountDefAuth().finally(() => {})
  if (code === 200) {
    if (data.avatar === '') data.avatar = data.sex === 0 ? `${import.meta.env.VITE_SHOUDAO_OSS_URL}/boy.svg` : `${import.meta.env.VITE_SHOUDAO_OSS_URL}/girl.png`
    storeCommit('userAvatar', data.avatar)
    storeCommit('zhiKeInfo', data)
  }
}
// 气泡弹窗倒计时
const isShowAiTip = ref(false)
let interId = 0
const countdownFn = () => {
  let time = 0
  interId = setInterval(() => {
    time += 1
    if (time > 120) {
      clearInterval(interId)
      isShowAiTip.value = true
    }
  }, 1000)
}
const goAIChatFn = () => {
  Router.push('ai_chat')
}

onShow(() => {
  countdownFn()
  getZhiKeInfo()
  getPopupInfoFn()
  isFirst.value = true
  getRecentInfoFn()
  getBannerList()
})

// 页面隐藏清除定时器
onHide(() => {
  isShowAiTip.value = false
  clearInterval(interId)
})
</script>

<style lang="less" scoped>
.wrap {
  position: absolute;
  .nav {
    z-index: 2;
    position: fixed;
    top: 0;
    left: 0;
  }
}
.banner {
  width: 750rpx;
  height: 580rpx;
  position: relative;
  .swiper-dot-d {
    z-index: 2;
    position: absolute;
    left: 50rpx;
    bottom: 160rpx;
    display: flex;
    .swiper-dot-item {
      height: 10rpx;
      border-radius: 20rpx;
      margin-right: 24rpx;
      transition: all .3s;
    }
  }
}
.body {
  width: 702rpx;
  position: relative;
  margin: -120rpx auto 0;
  .body_box {
    position: absolute;
    padding-bottom: 160rpx;
    .item_box {
      padding: 32rpx 32rpx 0 40rpx;
      width: 100%;
      background: white;
      border-radius: 24rpx;
      .nav_bar {
        border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
        padding-bottom: 34rpx;
        margin-bottom: 30rpx;
      }
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
        .num {
          font-size: 40rpx;
        }
        .label {
          font-size: 24rpx;
          color: #8c8c8c;
        }
      }
      .item1 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 292rpx;
        height: 116rpx;
        font-size: 28rpx;
        margin-bottom: 56rpx;
        .title {
          font-weight: 500;
          font-size: 28rpx;
          color: rgba(0,0,0,0.85);
          line-height: 40rpx;
        }
        .sub_title {
          font-weight: 400;
          font-size: 24rpx;
          color: rgba(0,0,0,0.65);
          line-height: 36rpx;
        }
      }
    }
    .new_info {
      width: 100%;
      margin: 32rpx auto 0;
      background: white;
      border-radius: 24rpx;
      min-height: 300rpx;
      .title {
        padding: 14rpx 24rpx;
        font-size: 24rpx;
        color: #8c8c8c;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .label {
          flex: 1 1;
        }
      }
      .item {
        font-size: 24rpx;
        color: rgba(0, 0, 0, 0.65);
        margin: 18rpx 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .info {
          flex: 1 1;
          display: flex;
          .message {
            flex: 1 1;
            max-width: 360rpx;
          }
        }
        .line {
          flex: 0 0 40rpx;
        }
        .time {
          flex: 0 0 auto;
          color: rgba(0, 0, 0, 0.25);
        }
      }
    }
  }
}
.pricacyPop {
  width: 100vw;
  padding: 0 20rpx;
  .title {
    font-size: 36rpx;
    font-weight: bolder;
    text-align: center;
    margin-top: 28rpx;
    margin-bottom: 28rpx;
  }
  .tips {
    width: 100%;
    font-size: 28rpx;
    padding-left: 5%;
    padding-right: 5%;
    margin-bottom: 32rpx;
  }
  .options {
    width: 100%;
    padding-left: 5%;
    padding-right: 5%;
    .firstPrav {
      width: 100%;
      display: flex;
      align-items: flex-start;
      margin-bottom: 20rpx;
      .rightItem {
        width: 90%;
        font-size: 28rpx;
        .fchkb {
          .schkb {
            color: #FF8002;
            word-break: break-all;
          }
        }
      }
    }
    .secondPrav {
      width: 100%;
      font-size: 28rpx;
      display: flex;
      .rightInfo {
        height: 56rpx;
        line-height: 56rpx;
      }
    }
  }
  .line {
    width: 100%;
    height: 1px;
    margin-top: 52rpx;
    background-color: rgba(192, 192, 192, .5);
  }
  .foot {
    width: 100%;
    display: flex;
    justify-content: space-around;
    margin-top: 36rpx;
    margin-bottom: 8rpx;
    font-size: 36rpx;
  }
}
.static_content {
  font-weight: 400;
  font-size: 28rpx;
  text-align: left;
  color: rgba(0,0,0,0.85);
  line-height: 40rpx;
  padding: 0 24rpx 0 26rpx;
}
.dynamic_content {
  font-weight: 600;
  font-size: 36rpx;
  color: #262626;
  line-height: 50rpx;
  text-align: left;
  padding: 0 30rpx;
}
.one_btn {
  width: 620rpx;
  height: 80rpx;
  font-size: 32rpx;
  font-weight: 500;
  color: #FFFFFF;
  line-height: 80rpx;
  text-align: center;
  background: #1890FF;
  border-radius: 47rpx;
}
.ai_chat {
  position: fixed;
  right: 20rpx;
  bottom: 200rpx;
  height: 160rpx;
  .bubble {
    position: relative;
    width: 330rpx;
    padding: 12rpx;
    font-size: 28rpx;
    border: 4rpx solid rgba(209, 209, 209, 1);
    border-radius: 16rpx;
    margin-right: 30rpx;
    background-color: #fff;
    .triangle_black {
      position: absolute;
      width: 0;
      height: 0;
      right: -20rpx;
      top: 35%;
      border-top: 10rpx solid transparent;
      border-bottom: 10rpx solid transparent;
      border-left: 20rpx solid rgba(209, 209, 209, 1);
    }
    .triangle_white {
      position: absolute;
      width: 0;
      height: 0;
      right: -17rpx;
      top: 35%;
      border-top: 10rpx solid transparent;
      border-bottom: 10rpx solid transparent;
      border-left: 20rpx solid #FFFFFF;
    }
  }
  .ai_avatar {
    position: relative;
    .ai_chat_text {
      position: absolute;
      bottom: 0;
      left: 20rpx;
      width: 78rpx;
      height: 35rpx;
      font-size: 20rpx;
      text-align: center;
      line-height: 35rpx;
      border-radius: 35rpx;
      background-color: #ffffff;
      box-sizing: border-box;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.25);
    }
  }
}
</style>
